package com.it.xzc.sandbox.utils;

import com.it.xzc.sandbox.model.ExecuteMessage;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class ProcessUtils {


    /**
     * 编译运行控制器
     * @param runProcess
     * @param opName
     * @return
     */
    public static ExecuteMessage runProcessAndGetExecuteMessage(Process runProcess,String opName) {
        ExecuteMessage executeMessage = new ExecuteMessage();
        try{
        //    等待程序执行，获取错误码
        int exitValue = runProcess.waitFor();
            executeMessage.setExitValue(exitValue);
        if (exitValue == 0) {
            System.out.println(opName+"成功");
            //    分批获取进程的正常输出
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
            StringBuilder compileOutputStringBuilder = new StringBuilder();
            //    逐行读取
            String compileOutputLine;
            while ((compileOutputLine = bufferedReader.readLine()) != null) {
                compileOutputStringBuilder.append(compileOutputLine);
            }
            String message = compileOutputStringBuilder.toString();
            executeMessage.setMessage( message);
            System.out.print(message);
        } else {
            //    异常退出
            System.out.println(opName+"失败，错误码：  " + exitValue);
            //    分批获取进程的正常输出
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
            StringBuilder compileOutputStringBuilder = new StringBuilder();
            //    逐行读取
            String compileOutputLine;
            while ((compileOutputLine = bufferedReader.readLine()) != null) {
                compileOutputStringBuilder.append(compileOutputLine);
            }
            //    分批获取进程的输出
            BufferedReader errorBufferReader = new BufferedReader(new InputStreamReader(runProcess.getErrorStream()));
            StringBuilder compileEroorOutputStringBuilder = new StringBuilder();
            //    逐行读取
            String errorCompileOutputLine;
            while ((errorCompileOutputLine = errorBufferReader.readLine()) != null) {
                compileEroorOutputStringBuilder.append(errorCompileOutputLine);
            }
            String errorMessage = compileOutputStringBuilder.toString();
            executeMessage.setErrorMessage(errorMessage);
            System.out.print(errorMessage);
        }
    }catch(Exception e){
        throw new RuntimeException(e);
    }
        return executeMessage;
}
}
